﻿using NetCommand;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DtuService
{
    class UserService : IService
    {
        private Dictionary<int, User> userDic = new Dictionary<int, User>();
        public void Init()
        {
            
        }

        public void InsertUser(int id, User user)
        {
            if (userDic.ContainsKey(id))
            {/// 顶掉旧的客户端
                NetCommand.ServerShutdownCommand serverShutdown = new ServerShutdownCommand();
                userDic[id].SendMessage(serverShutdown);
                userDic[id].Shutdown();
            }
            userDic.Add(id, user);
        }

        public void RemoveUser(int id)
        {
            if (userDic.ContainsKey(id))
            {
                userDic.Remove(id);
            }
        }

        public User GetUser(int id)
        {
            if (userDic.ContainsKey(id))
            {
                return userDic[id];
            }
            return null;
        }

        public void Tick(float time)
        {
            foreach (KeyValuePair<int, User> user in userDic)
            {
                user.Value.Update(time);
            }
        }

        public void Shutdown()
        {
            foreach (KeyValuePair<int, User> user in userDic)
            {
                user.Value.Shutdown();
            }
            userDic.Clear();
        }
    }
}
